package com.wxhandle.cleandemo.api.config;

import com.wxhandle.cleandemo.api.security.DefaultAccessDecisionManager;
import com.wxhandle.cleandemo.api.security.DefaultFilterSecurityInterceptor;
import com.wxhandle.cleandemo.api.security.DefaultInvocationSecurityMetadataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import lombok.RequiredArgsConstructor;

/**
 * @author sean.kei
 */
@RequiredArgsConstructor
@EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        // .antMatchers("/**/**")
        .antMatchers("/swagger**/**", "/webjars/**", "/v3/**", "/doc.html", "/error");
    }


	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		.authorizeRequests()
			.anyRequest().authenticated()
			.and()
		.csrf().disable()
		.cors().and()
		.oauth2ResourceServer()
			.jwt();
        DefaultFilterSecurityInterceptor filter= new DefaultFilterSecurityInterceptor();
        filter.setSecurityMetadataSource(new DefaultInvocationSecurityMetadataSource());
        filter.setDefaultAccessDecisionManager(new DefaultAccessDecisionManager());
        // DefaultMethodSecurityInterceptor method = new DefaultMethodSecurityInterceptor();
		http.addFilterBefore(filter, FilterSecurityInterceptor.class);
	}
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}
